//
//  AccountTradeDetailView.m
//  NOAHWM
//
//  Created by Ryan on 13-6-25.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "AccountTradeDetailView.h"
#import "NYTradeDetail.h"
#import "TradeDetailCell.h"
#import "TradeSeperateCell.h"
#import "JSON.h"

#define kTouZiColor [UIColor colorWithRed:72.f/255 green:117.f/255 blue:30.f/255 alpha:1.f]
#define kFenPeiColor [UIColor colorWithRed:240.f/255 green:109.f/255 blue:54.f/255 alpha:1.f]

@implementation AccountTradeDetailView

@synthesize touziLabel,fenpeiLabel,tradeTableView,bizhongLabel;
@synthesize tradeDetails;
@synthesize panView;
@synthesize isTop;
@synthesize placeHolderImageView;

#pragma mark - Public methods
- (void)showTradeDetailView:(BOOL)show
{
    UIView *relativeView = self.superview;
    CGRect tradeViewRect = self.frame;
    if(show)
    {
        tradeViewRect.origin.y = kNaviHeaderHeight;
    }
    else
    {
        tradeViewRect.origin.y = relativeView.frame.size.height-kNaviHeaderHeight;
    }
    [UIView animateWithDuration:0.3f animations:^(void){
        self.frame = tradeViewRect;
    }];
    self.isTop = show;
}


- (void)callServerToGetTradeDetailWithAccountId:(NSString *)accountId
                                      productId:(NSString *)productId
{
    NSString *suburl = [NSString stringWithFormat:kAccountTradeDetailUrl,@"jsonp",accountId,productId,@""];
    suburl = [suburl stringByAppendingString:@"app000031"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

- (void)panWithGesture:(UIPanGestureRecognizer *)panGesture
{
    UIView *relativeView = self.superview;
    
    CGRect rectForSelf = self.frame;
    
    CGPoint translationPoint = [panGesture translationInView:relativeView];
    CGFloat moveY = translationPoint.y;
    
    CGPoint currentVelocityPoint = [panGesture velocityInView:relativeView];
    CGFloat currentVelocityY     = currentVelocityPoint.y;
    
    if(panGesture.state == UIGestureRecognizerStateEnded || panGesture.state == UIGestureRecognizerStateCancelled)
    {
        if(currentVelocityY > 0)
            [self showTradeDetailView:NO];
        else
            [self showTradeDetailView:YES];
    }
    else
    {
        if(self.isTop)
        {
            rectForSelf.origin.y = kNaviHeaderHeight+moveY;
        }
        else
        {
            rectForSelf.origin.y = relativeView.frame.size.height-kNaviHeaderHeight+moveY;
        }
        if(rectForSelf.origin.y < kNaviHeaderHeight)
            rectForSelf.origin.y = kNaviHeaderHeight;
        if(rectForSelf.origin.y > relativeView.frame.size.height-kNaviHeaderHeight)
            rectForSelf.origin.y = relativeView.frame.size.height-kNaviHeaderHeight;
        self.frame = rectForSelf;
    }
}

- (void)tapWithGesture:(UITapGestureRecognizer *)tapGesture
{
    [self showTradeDetailView:!self.isTop];
}
#pragma mark - UIView methods

- (void)awakeFromNib
{
    [super awakeFromNib];
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panWithGesture:)];
    [self.panView addGestureRecognizer:panGesture];
    [panGesture release];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapWithGesture:)];
    [self.panView addGestureRecognizer:tapGesture];
    [tapGesture release];
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [placeHolderImageView release];
    [bizhongLabel release];
    [panView release];
    [tradeDetails release];
    [touziLabel release];
    [fenpeiLabel release];
    [tradeTableView release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.tradeDetails.count == 0)
        return 0;
    if(self.tradeDetails.count == 1)
        return 1;
    else
        return self.tradeDetails.count+self.tradeDetails.count-1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row%2 != 0)
    {
        static NSString *seperateCellIdentify = @"seperateCellIdentify";
        TradeSeperateCell *seperateCell = [tableView dequeueReusableCellWithIdentifier:seperateCellIdentify];
        if(nil == seperateCell)
        {
            NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"TradeSeperateCell" owner:self options:nil];
            seperateCell = [nibs lastObject];
            seperateCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return seperateCell;
    }
    else
    {
        static NSString *tradeCellIdentify = @"tradeCellIdentify";
        TradeDetailCell *tradeCell = [tableView dequeueReusableCellWithIdentifier:tradeCellIdentify];
        if(nil == tradeCell)
        {
            NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"TradeDetailCell" owner:self options:nil];
            tradeCell = [nibs lastObject];
            tradeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSInteger index = indexPath.row/2;
        NYTradeDetail *nytd = [self.tradeDetails objectAtIndex:index];
        tradeCell.dateLabel.text = nytd.act_date;
        
        if([nytd.deal_status isEqualToString:@"待生效"])
            tradeCell.dateLabel.text = @"待生效";
        
        tradeCell.leixingLabel.text = nytd.trade_type_detail;
        if([nytd.is_invest isEqualToString:@"1"])
        {
            tradeCell.touziLabel.text = nytd.amount_total;
            tradeCell.fenpeiLabel.text = @"";
            tradeCell.iconImageView.image = [UIImage imageNamed:@"icon_trade_touzi@2x.png"];
            tradeCell.leixingLabel.textColor = kTouZiColor;
            tradeCell.touziLabel.textColor = kTouZiColor;
            tradeCell.fenpeiLabel.textColor = kTouZiColor;
        }
        else
        {
            tradeCell.fenpeiLabel.text = nytd.amount_total;
            tradeCell.touziLabel.text = @"";
            tradeCell.iconImageView.image = [UIImage imageNamed:@"icon_trade_fenpei@2x.png"];
            tradeCell.leixingLabel.textColor = kFenPeiColor;
            tradeCell.touziLabel.textColor = kFenPeiColor;
            tradeCell.fenpeiLabel.textColor = kFenPeiColor;
        }
        return tradeCell;
    }
}

#pragma mark - UITableViewDelegate methods

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row%2 != 0)
    {
        return kTradeSeperateCellHeight;
    }
    else
    {
        return kTradeDetailCellHeight;
    }
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        self.tradeTableView.hidden = NO;
        self.placeHolderImageView.hidden = YES;
        self.fenpeiLabel.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"allotMoneyTotal"]];
        self.touziLabel.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"investMoneyTotal"]];
        self.bizhongLabel.text = [dict objectForKey:@"productcurrency"];
        self.tradeDetails = [NSMutableArray array];
        NSArray *array = [dict objectForKey:@"list"];
        for(NSDictionary *tradeDict in array)
        {
            NYTradeDetail *nytd = [[NYTradeDetail alloc] init];
            for(NSString *key in [tradeDict allKeys])
            {
                id value = [tradeDict objectForKey:key];
                @try {
                    [nytd setValue:value forKey:key];
                }
                @catch (NSException *exception) {
                    NSLog(@"试图添加不存在的key: %@到NYTradeDetail实例中.",key);
                }
            }
            [self.tradeDetails addObject:nytd];
            [nytd release];
        }
        [self.tradeTableView reloadData];
    }
    else
    {
//        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    self.tradeTableView.hidden = YES;
    self.placeHolderImageView.hidden = NO;
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}


@end
